import {net, app} from 'electron'

export stream2buffer = (s)=>
  s = await s
  r = []
  push = r.push.bind r
  s.on 'data',push
  new Promise (resolve, reject) =>
    s.on 'end', =>
      resolve Buffer.concat r
      return
    s.on 'error', reject

export stream2utf8 = (s)=>
  s = await stream2buffer s
  s.toString 'utf8'

export stream2json = (s)=>
  JSON.parse await stream2utf8 s

export get = (url)=>
  stream2buffer get_stream(url)

_wait = (opt)=>
  req = net.request opt
  req.end()
  new Promise (resolve, reject)=>
    req.on 'error',(err)=>
      reject(err)
      return
    req.on 'response',(r)=>
      if r.statusCode != 200
        reject r
        return
      resolve(r)
      return

export get_stream = (url)=>
  _wait url

export post = (url)=>
  _wait {
    method: 'POST'
    url
  }
